<script setup>
import {onMounted, onUnmounted, ref} from "vue";
import {httpGet, httpPost, httpPostDownload} from "@/utils/http.js";
import {ElMessage} from "element-plus";
import {dateFormat, substr, UUID} from "@/utils/libs.js";
import {DocumentCopy, Plus, Search} from "@element-plus/icons-vue";
import ClipboardJS from "clipboard";

// 变量定义
// 列表数据
const items = ref([])
// 数据加载标识
const loading = ref(true)
// 查询条件
const query = ref({code: "", status: -1})
// 兑换码状态
const redeemStatus = ref([
  {value: -1, label: "全部"},
  {value: 0, label: "未销毁"},
  {value: 1, label: "已销毁"},
])
// 弹框状态
const showDialog = ref(false)
// 弹框加载标识
const dialogLoading = ref(false)
// 添加或者编辑对象
const item = ref({name: '', power: 0, num: 1})
// 兑换码选中Id集合
const itemIds = ref([])
// 导出按钮加载动画是否启用
const exportingLoading = ref(false)
// 页码
const page = ref(1)
// 每页数量
const pageSize = ref(12)
// 数据总数
const total = ref(0)
const clipboard = ref(null)

onMounted(() => {
  // 绑定标签
  clipboard.value = new ClipboardJS('.copy-code')
  // 注册事件
  clipboard.value.on('success', () => {
    ElMessage.success('复制成功！')
  })
  clipboard.value.on('error', () => {
    ElMessage.error('复制失败！')
  })
  // 初始化表格数据
  fetchData()
})

onUnmounted(() => {
  // 移除事件监听器
  clipboard.value.destroy()
})

// 打开对话框
const add = () => {
  // 设置默认属性
  item.value = {name: '100算力点卡', power: 100, num: 1}
  showDialog.value = true
  dialogLoading.value = false
}

// 生成兑换码
const save = () => {
  if (item.value.name === '') {
    return ElMessage.error('请输入兑换码名称')
  }

  if (item.value.power === '') {
    return ElMessage.error('请输入算力额度')
  }

  if (item.value.num <= 0) {
    return ElMessage.error('请输入生成数量')
  }
  dialogLoading.value = true
  httpPost('api/admin/redeem/create', item.value).then(res => {
    ElMessage.success(`成功生成了${res.data.counter}个兑换码`)
    fetchData()
    // 关闭对话框
    showDialog.value = false
  }).catch(e => {
    ElMessage.error("生成失败：" + e.message)
    dialogLoading.value = false
  })
}

// 设置对应字段的值，点击启用状态触发
const set = (filed, row) => {
  httpPost('api/admin/redeem/set', {id: row.id, filed: filed, value: row[filed]}).then(() => {
    ElMessage.success("操作成功")
  }).catch(e => {
    ElMessage.error("操作失败：" + e.message)
  })
}

// 查询列表数据
const fetchData = () => {
  query.value.page = page.value
  query.value.page_size = pageSize.value
  loading.value = true
  httpGet('api/admin/redeem/list', query.value).then(res => {
    if (res.data) {
      items.value = res.data.items
      total.value = res.data.total
      page.value = res.data.page
      pageSize.value = res.data.page_size
    }
    loading.value = false
  }).catch(e => {
    ElMessage.error("获取列表数据失败：" + e.message)
    loading.value = false
  })
}

// 删除数据触发
const remove = (row) => {
  httpGet("api/admin/redeem/remove?id=" + row.id).then(() => {
    ElMessage.success("删除成功。")
    // 调用查询列表数据方法
    fetchData()
  }).catch(e => {
    ElMessage.error("删除失败：" + e.message)
  })
}

// 表格选择数据时触发，收集选择的数据Id
const handleSelectionChange = (items) => {
  itemIds.value = items.map(item => item.id)
}

// 导出兑换码
const exportItems = () => {
  query.value.ids = itemIds.value
  exportingLoading.value = true
  httpPostDownload('api/admin/redeem/export', query.value).then(res => {
    // 将服务器返回的二进制数据（res.data）转换为浏览器可识别的临时 URL
    // 通过 Blob 构造函数将原始数据（res.data，可能是二进制流或文本）包装成一个 Blob 对象。Blob 表示不可变的原始数据，常用于处理文件、图像等二进制内容
    // window.URL.createObjectURL 将 Blob 对象转换为临时 URL（如 blob:http://example.com/550e8400-e29b-41d4-a716-446655440000），该 URL 仅在当前文档生命周期内有效，可直接用于 <img>、<a> 等标签的资源引用。
    const url = window.URL.createObjectURL(new Blob([res.data]))
    // 创建一个 a 标签
    const link = document.createElement('a')
    link.href = url
    // 设置下载文件的名称
    link.setAttribute('download', UUID() + ".csv")
    // 把标签加入到根节点中
    document.body.appendChild(link)
    // 触发点击下载
    link.click()
    // 移除 <a> 标签
    document.body.removeChild(link)
    // 释放用过 window.URL.createObjectURL 创建的 URL 对象，防止内存泄露
    window.URL.revokeObjectURL(url)
    exportingLoading.value = false
  }).catch(e => {
    exportingLoading.value = false
    ElMessage.error("下载失败：" + e.message)
  })
}

</script>

<template>
  <div class="container list" v-loading="loading">
    <div class="handle-box">
      <el-input v-model="query.code" placeholder="兑换码" class="handle-input mr10"></el-input>
      <el-select v-model="query.status" placeholder="核销状态" style="width: 100px" class="handle-input mr10">
        <el-option
            v-for="item in redeemStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
      <el-button type="primary" :icon="Search" @click="fetchData">搜索</el-button>
      <el-button type="success" :icon="Plus" @click="add">添加兑换码</el-button>
      <el-button type="primary" @click="exportItems" :loading="exportingLoading"><i
          class="iconfont icon-export mr-1"></i>导出</el-button>
    </div>
    <el-row>
      <el-table :data="items" :row-key="row => row.id" @selection-change="handleSelectionChange" table-layout="auto">
        <el-table-column type="selection" width="38"></el-table-column>
        <el-table-column prop="name" label="名称"/>
        <el-table-column prop="code" label="兑换码">
          <template #default="scope">
            <span>{{ substr(scope.row.code, 24) }}</span>
            <el-icon class="copy-code" :data-clipboard-text="scope.row.code">
              <DocumentCopy/>
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column label="兑换人">
          <template #default="scope">
            <span v-if="scope.row['username'] !== ''">{{ scope.row['username'] }}</span>
            <el-tag v-else>未兑换</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="power" label="算力"/>
        <el-table-column label="生成时间">
          <template #default="scope">
            <span>{{ dateFormat(scope.row['created_at']) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="兑换时间">
          <template #default="scope">
            <span v-if="scope.row['redeemed_at'] > 0 ">{{ dateFormat(scope.row['redeemed_at']) }}</span>
            <el-tag v-else>未兑换</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="enabled" label="启用状态">
          <template #default="scope">
            <el-switch
                v-model="scope.row['enabled']"
                @change="set('enabled',scope.row)"
                :disabled="scope.row['redeemed_at'] > 0"
            />
          </template>
        </el-table-column>
        <el-table-column width="180" label="操作">
          <template #default="scope">
            <el-popconfirm title="确定要删除当前记录吗？" @confirm="remove(scope.row)">
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-row>

    <div class="pagination">
      <el-pagination v-if="total > 0" background
                     layout="total,prev, pager, next"
                     :hide-on-single-page="true"
                     v-model:current-page="page"
                     v-model:page-size="pageSize"
                     @current-change="fetchData()"
                     :total="total"/>

    </div>

    <el-dialog v-model="showDialog" title="生成兑换码">
      <template #default>
        <el-form :model="item" label-width="120px" v-loading="dialogLoading">
          <el-form-item label="名称：" prop="name">
            <el-input v-model="item.name" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="算力额度：" prop="power">
            <el-input v-model.number="item.power" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="生成数量：" prop="num">
            <el-input v-model.number="item.num"/>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
          <span class="dialog-footer">
            <el-button @click="showDialog = false">取消</el-button>
            <el-button type="primary" @click="save">提交</el-button>
          </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="stylus">
.list {
  .handle-box {
    margin-bottom 20px

    .handle-input {
      max-width 150px;
      margin-right 10px;
    }
  }

  .opt-box {
    padding-bottom: 10px;
    display flex;
    justify-content flex-end

    .el-icon {
      margin-right: 5px;
    }
  }

  .el-select {
    width: 100%
  }

  .copy-code {
    cursor pointer
    margin-left 6px
    position relative
    top 2px
    font-size 14px
  }

  .pagination {
    margin-top: 20px;
    display flex;
    justify-content: right;
  }

}
</style>